package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.writing.entity.Corpus;
import com.writing.mapper.CorpusMapper;
import com.writing.service.CorpusService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 语料库Service实现类
 */
@Service
public class CorpusServiceImpl extends ServiceImpl<CorpusMapper, Corpus> implements CorpusService {

    @Override
    public List<Corpus> getCorpusByNovelId(Long novelId) {
        return this.list(new LambdaQueryWrapper<Corpus>()
                .eq(Corpus::getNovelId, novelId)
                .orderByDesc(Corpus::getCreatedAt));
    }

    @Override
    public Corpus getCorpusById(Long corpusId, Long novelId) {
        return this.getOne(new LambdaQueryWrapper<Corpus>()
                .eq(Corpus::getId, corpusId)
                .eq(Corpus::getNovelId, novelId));
    }

    @Override
    public Corpus createCorpus(Corpus corpus) {
        // 设置默认类型
        if (corpus.getType() == null) {
            corpus.setType("description");
        }

        this.save(corpus);
        return corpus;
    }

    @Override
    public Corpus updateCorpus(Corpus corpus) {
        // 验证语料库是否存在
        Corpus existingCorpus = this.getOne(new LambdaQueryWrapper<Corpus>()
                .eq(Corpus::getId, corpus.getId())
                .eq(Corpus::getNovelId, corpus.getNovelId()));

        if (existingCorpus == null) {
            throw new RuntimeException("语料库不存在");
        }

        this.updateById(corpus);
        return corpus;
    }

    @Override
    public boolean deleteCorpus(Long corpusId, Long novelId) {
        Corpus corpus = getCorpusById(corpusId, novelId);
        if (corpus == null) {
            throw new RuntimeException("语料库不存在");
        }

        return this.removeById(corpusId);
    }
}
